package cn.tianyigps.tianyigpsapiv2.service;

import cn.tianyigps.tianyigpsapiv2.dao.FenceDao;
import cn.tianyigps.tianyigpsapiv2.param.dto.FenceDTO;
import cn.tianyigps.tianyigpsapiv2.param.dto.PageDTO;
import cn.tianyigps.tianyigpspublic.bean.GeoFence;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.geo.GeoJsonPolygon;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: LiuHao
 * @Descirption:
 * @Date: 2019/4/3_9:24
 */
@Slf4j
@Service
public class FenceService {

    @Autowired
    private FenceDao fenceDao;

    public GeoFence insert(FenceDTO fenceDTO) throws RuntimeException {
        //入参处理
        GeoFence geoFence = new GeoFence();
        BeanUtils.copyProperties(fenceDTO, geoFence);
        List<Point> points = fenceDTO.getPoints()
                .stream()
                .map(point -> new Point((Double) point.get("x"), (Double) point.get("y")))
                .collect(Collectors.toList());
        geoFence.setPolygon(new GeoJsonPolygon(points));
        //保存
        fenceDao.insert(geoFence);
        return geoFence;
    }

    public boolean logicRemove(String id) {
        return fenceDao.logicRemove(id);
    }

    public GeoFence detail(String id) {
        return fenceDao.findOne(id);
    }

    public boolean update(FenceDTO fenceDTO) {
        Update update = new Update();
        update.set("group", fenceDTO.getGroup());
        update.set("tags", fenceDTO.getTags());
        update.set("description", fenceDTO.getDescription());
        UpdateResult result = fenceDao.updateFirst(fenceDTO.getId(), update);
        return result.isModifiedCountAvailable();
    }

    public PageDTO<List<GeoFence>> getGeoFenceList(String group, int page, int limit) {
        return fenceDao.getGeoFenceList(group, page, limit);
    }

    public Set<String> getGroupNameSet(int page, int limit) {
        //取出所有group，去重,去空
        return fenceDao.getGeoFenceList(null, page, limit).getData()
                .stream().map(geoFence -> geoFence.getGroup()).collect(Collectors.toSet())
                .stream().filter(group -> Optional.ofNullable(group).isPresent()).collect(Collectors.toSet());
    }

}
